from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Max,Q,F,Min,Avg,Count,Sum
from django.contrib.auth.hashers import make_password,check_password
import datetime  #导入时间包
import time
import random
from utils.coom  import *
from django.http import HttpResponse

from .ser import *

# Create your views here.

class Cart111m(APIView):
    def get(self,request):
        cart = Cart111.objects.all()
        ser = Cart111mSer(cart,many=True)
        return Response({"code":200,'list':ser.data})


#注册
import re
class UserRegister(APIView):
    def post(self,request):
        #用户名
        username = request.data.get('username')
        if not username:
            return Response({"code":11000})
        if not re.match('^\w{5,10}$',username):
            return Response({"code": 11001})
        user = USerregister.objects.filter(username=username).first()
        if user == username:
            return Response({"code": 11002})
        return Response({"code":200})

        #密码
        password = request.data.get('password')
        if not password:
            return Response({"code": 11003})
        if not re.match('^\w{8,20}$', password):
            return Response({"code": 11004})

        #判断验证码
        veris = request.data.get('veris')
        # 1.链接
        coom = get_redis_conn()
        #2.获取
        yanz = coom.get(num)
        if veris:
            veriss = str(veris,encoding='utf8')
        if veriss == yanz:
            return Response({"code":11005})



        # return Response({"code": 200})

import redis
#验证码
class Verimanage(APIView):
    def post(self,request):
        #点击图形验证码变换的id #主要用来获取redis储存的图形验证码
        uuid = request.data.get('uuid')
        #图片验证 （类似A4G4）
        # 验证码
        cpatchas = request.data.get('cpatchas')
        print(cpatchas)
        mobile = request.data.get('mobile')
        #获取redis储存的uuid的图形码
        comm = get_redis_conn()#  先连接后获取
        imgurl = comm.get(uuid)   #获取到储存在redis的图形验证码
        print(mobile)
        print(imgurl)
        if imgurl:  #如果有储存了的图形验证码
            imgurl = str(imgurl,encoding='utf8') #先转格式不然不会识别
            if imgurl.lower() == cpatchas.lower(): #前端图形验证码和后端redis中厨房的对比
                num = random.randint(1000, 9999)  #生成随机验证码
                print(num)
                res =send_message(mobile, num, 1)  #给接收到的手机号发送验证码
                if res:  #如果验证码发送了
                    # redis保存
                    # 1.链接
                    com = get_redis_conn() #链接redis
                    # # 2.保存
                    com.setex(mobile, 60, num)  #保存60秒发送的验证码  方便判断
                    return Response({'code': 200})
        return Response({'code': 20010})


#注册
class ZhuCe(APIView):
    def post(self,request):
        # 注册添加
        ser = UserRegisterSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})


    #判断登录次数
    def get(self,request):
        userid = request.GET.get('userid')
        newid = request.GET.get('newid')

        #开启redis
        coom = get_redis_conn()
        #添加值
        count = coom.hincrby(userid,newid)
        print(count) #b^1^
        if int(count)>3:
            return Response({"code":20010,'mes':'只能查看三次'})
        else:
            return Response({'code':200})








#登录
class Loginmanage(APIView):
    #登录用户获取用户id
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = USerregister.objects.filter(username=username).first()
        if user:
            if password == user.password:
                return Response({"code": 200,'userid':user.id})
            else:
                return Response({"code": 20010,'mes':'密码错误'})
        else:
            return Response({'code':10010,'mes':'用户不存在'})

    # 获取新闻
    def get(self, request):
        new = NewPress.objects.all()
        ser = CarLoginmanageSer(new, many=True)
        return Response({"code": 200, 'list': ser.data})


#图形验证码
from utils.captcha.captcha import captcha
class CapTcha(APIView):
    def get(self,request):
        #使用三方包
        name,text,img = captcha.generate_captcha()
        print(text)
        #开启redis
        coom = get_redis_conn()
        #储存uuid
        uuid = request.GET.get('uuid')
        coom.set(uuid,text)
        return HttpResponse(img,content_type='image/jpg')




























